package com.viettel.pon.Tabs;

import java.security.PublicKey;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Currency;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;
import org.apache.log4j.lf5.viewer.TrackingAdjustmentListener;

import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.viettel.maps.MapView;
import com.viettel.maps.MapView.OnMyLocationButtonClickListener;
import com.viettel.maps.base.LatLng;
import com.viettel.maps.layers.InfoBoxLayer;
import com.viettel.maps.layers.MapLayer;
import com.viettel.maps.layers.MarkerLayer;
import com.viettel.maps.layers.MapLayer.OnDoubleClickListener;
import com.viettel.maps.objects.InfoWindow;
import com.viettel.maps.objects.InfoWindowOptions;
import com.viettel.maps.objects.MapObject;
import com.viettel.maps.objects.Marker;
import com.viettel.maps.objects.MarkerOptions;
import com.viettel.maps.objects.Polyline;
import com.viettel.maps.objects.PolylineOptions;
import com.viettel.maps.util.AppInfo;
import com.viettel.maps.util.MapConfig;
import com.viettel.maps.util.MapConfig.SRSType;
import com.viettel.pon.R;
import com.viettel.pon.common.Constant;
import com.viettel.pon.common.DataBaseHelper;
import com.viettel.pon.common.DialogCommon;
import com.viettel.pon.common.GPSTracker;
import com.viettel.pon.common.GlobalClass;
import com.viettel.pon.common.MapFunction;
import com.viettel.pon.common.Spin;
import com.viettel.pon.config.Config;
import com.viettel.pon.form.HouseForm;
import com.viettel.pon.form.InfomationForm;
import com.viettel.pon.form.PoleForm;
import com.viettel.pon.form.PositionForm;
import com.viettel.pon.main.MainActivity;
import com.viettel.pon.storage.MapCache;
import java.text.DecimalFormat;

import javax.security.auth.PrivateCredentialPermission;

import android.graphics.Bitmap;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.widget.CompoundButton;
import android.widget.ToggleButton;


import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;


public class ViewActivity extends Fragment {
	/*
	 * declare
	 */
	private static final String VNCHAR = "^([a-zA-Z0-9\\_/]+)$";
	private static final String SPECIALCHAR = "/^[^\\`\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\+\\=\\<\\>\\?\\-\\/]*$/";
	protected static final String TAG = "ViewActivity";
	private Logger mLog;
	private TextView txtKinhdo,txtVido;
	private EditText edtKinhdo, edtVido;
	
	
	
	private TextView txtMacotdien;
	private TextView txtLoaicotdien;
	private TextView txtChusohuu;
	private TextView txtSohodan;
	private TextView txtGhichu;
	private EditText edtMacotdien;
	private EditText edtSohodan;
	private EditText edtGhichu;
	private Button btnSave,btnExit;
	private Button btnCancelPoles;
	private RadioGroup rdoLoaicotdien;
	private RadioGroup rdoChusohuu;
	private CheckBox chkNewOrOld;
	private RadioButton rbLoaicotdien;
	private RadioButton rbChusohuu;
	RadioGroup rdoPosition;
	View popupViewHouse;
	PopupWindow popupWindowHouse;
	private MapView mapView;
	private Marker currentMaker;
	private ImageButton ibnStart;
	// private ImageButton ibnEnd;
	private ImageButton ibnHouse, ibnPoles, ibnPlace, ibnRoad;
	private ImageButton ibnRoad32, ibnPlace32, ibnHouse32, ibnPoles32;
	// private ImageButton ibnPoles1;
	private ImageButton ibnPause;
	private TextView txtViewBottom;
	private EditText edtPlaceDescription;
	private EditText edtPlaceName;
	private Button btnInsert;
	private Button btnCancelPlace;
	private RelativeLayout layoutToReplaceAll;
	ArrayList<LatLng> listPointOfCurrentRoad = new ArrayList<LatLng>();
	PolylineOptions currentRoad = new PolylineOptions();
	PolylineOptions polylineoption =new PolylineOptions();
	ArrayList<Polyline> lstcurrentdiscreteRoad = new ArrayList<Polyline>();
	//ArrayList<Polyline>
	LatLng geoPoint;
	private Handler mHandler = new Handler();
	// private Handler mHandler1 = new Handler();
	GPSTracker gps = null;
	
	Timer timer;
	TimerTask doAsynchronousTask;
	DataBaseHelper db;
	private long secs, mins, hrs, msecs;
	private String hours, minutes, seconds, milliseconds;
	private final int REFRESH_RATE = 100;
	private long startTime;
	private long elapsedTime;
	private boolean stopped = true;
	// public boolean isToggle;
	private View rootView;
	private Context _context;
	private GlobalClass _glb;
	DialogCommon _dlg;
	private int idTime = 0;
	List<InfomationForm> lstTime = new ArrayList<InfomationForm>();
	PopupWindow PopupWindowPole, PopupWindowPlace, PopupWindowUpdate; 
	View popupViewPoles, popupViewPlaces, popupViewUpdate;
	private Polyline currentPolyline = new Polyline(currentRoad);
	private MarkerLayer markerLayer;
	private ImageButton ibnSwitch1;
	private ImageButton ibnSwitch2;
	private boolean checkSwitch = false;
	private boolean rawLine = false;
//	private boolean showPopup;
	int count = 0;
	private ImageButton ibnRawLine1;
	private ImageButton ibnRawLine2;

	private ToggleButton toggle;
	private double lon, lat;

	private int mHeaderMode = 20;
	//private static final LatLng gps.longitude= 122;
	private static final int HEADER_MODE_POLE = 0;
	private static final int HEADER_MODE_PLACE = 1;
	private static final int HEADER_MODE_HOUSE = 2;
	private static final int HEADER_MODE_ROAD = 3;
	private static final int HEADER_MODE_POLE32 = 4;
	private static final int HEADER_MODE_PLACE32 = 5;
	private static final int HEADER_MODE_HOUSE32 = 6;
	private static final int HEADER_MODE_ROAD32 = 7;

	Bitmap markerIcon = null;
	private int idUpdate;
	//ArrayList<MarkerOptions> tempMarker = new ArrayList<MarkerOptions>();
	ArrayList<Marker> listMarkerDrawRoad = new ArrayList<Marker>();
	ArrayList<MarkerOptions> listMarkerDrawRoadOption = new ArrayList<MarkerOptions>();
	ArrayList<LatLng> listPointOfCurrentRoad_ = new ArrayList<LatLng>();
	boolean dialogShown = false;

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			final Bundle savedInstanceState) {
		mLog = Logger.getLogger(ViewActivity.class);
		MapConfig.changeSRS(SRSType.SRS_4326);
		_context = getActivity().getApplicationContext();

		db = new DataBaseHelper(_context);
		gps = new GPSTracker(getActivity());
		_glb = (GlobalClass) _context.getApplicationContext();
		rootView = inflater.inflate(R.layout.activity_map, container, false);
		mapView = (MapView) rootView.findViewById(R.id.idMapView);

		markerLayer = new MarkerLayer();
		markerLayer.setZoomRange(11, 19);
		mapView.addLayer(markerLayer);

		_dlg = new DialogCommon(getActivity());
		AppInfo.enableDebugMode(true);
		String myTag = getTag();
		((MainActivity) getActivity()).setTabView(myTag);
		ibnStart = (ImageButton) rootView.findViewById(R.id.ibnStart);
		// ibnEnd = (ImageButton) rootView.findViewById(R.id.ibnEnd);
		ibnHouse = (ImageButton) rootView.findViewById(R.id.ibnHouse);
		ibnHouse32 = (ImageButton) rootView.findViewById(R.id.ibnHouse32);
		ibnPlace = (ImageButton) rootView.findViewById(R.id.ibnPlace);
		ibnPlace32 = (ImageButton) rootView.findViewById(R.id.ibnPlace32);
		ibnPoles = (ImageButton) rootView.findViewById(R.id.ibnPoles);
		ibnPoles32 = (ImageButton) rootView.findViewById(R.id.ibnPoles32);
		ibnPause = (ImageButton) rootView.findViewById(R.id.ibnPause);
		ibnSwitch1 = (ImageButton) rootView.findViewById(R.id.ibnSwitch1);
		ibnSwitch2 = (ImageButton) rootView.findViewById(R.id.ibnSwitch2);
		ibnRawLine1 = (ImageButton) rootView.findViewById(R.id.ibnRawLine1);
		ibnRawLine2 = (ImageButton) rootView.findViewById(R.id.ibnRawLine2);
		txtViewBottom = (TextView) rootView.findViewById(R.id.txtViewBottom);
		toggle = (ToggleButton) rootView.findViewById(R.id.togglebutton);
		layoutToReplaceAll = (RelativeLayout) rootView
				.findViewById(R.id.layoutToReplaceAll);
		rootView.findViewById(R.id.header).setVisibility(LinearLayout.GONE);
		lstTime = db.getAllTimeStop();

		// anhpt67
		ibnRoad = (ImageButton) rootView.findViewById(R.id.ibnRoad);
		ibnRoad32 = (ImageButton) rootView.findViewById(R.id.ibnRoad32);
		ibnRoad.setVisibility(View.GONE);	
		
		//Lấy đối tượng Spinner ra
		Spinner spinner = (Spinner) rootView.findViewById(R.id.planets_spinner);
		
		 //Gán Data source (arr) vào Adapter
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
		        R.array.planets_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource
		 (android.R.layout.simple_list_item_single_choice);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		// thiết lập sự kiện chọn phần tử cho spinner
		/*spinner.setOnItemSelectedListener(new MyProcessEvent());
	 }*/
		
		
		
		
	

		
		/*Spinner spinner = (Spinner) rootView.findViewById(R.id.planets_spinner);
		List<Spin> trangThai = new ArrayList<Spin>();
        trangThai.add(new Spin("3", "Tất cả"));
        trangThai.add(new Spin("1", "ứng hòa"));
        trangThai.add(new Spin("2", "hòa bình"));
        ArrayAdapter<Spin> dataAdapterType = new ArrayAdapter<Spin>(getActivity(),
                     android.R.layout.simple_spinner_item, trangThai);
        dataAdapterType
                     .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapterType);*/

		
		if (_glb.getFlag() != null && _glb.getFlag().equals(1)
				&& stopped != true) {
			_glb.setFlag(0);
		}
	
		// Bat dau khao sat
		ibnStart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Button Start click");
				_glb.setFlagMap(1);
				MapCache.isStarting = true;
				ibnStart.setVisibility(View.GONE);
				ibnPause.setVisibility(View.VISIBLE);
				toggle.setVisibility(View.GONE);
				ibnRoad32.setVisibility(View.GONE);
				ibnPoles32.setVisibility(View.GONE);
				ibnPlace32.setVisibility(View.GONE);
				ibnHouse32.setVisibility(View.GONE);
				ibnPoles.setVisibility(View.VISIBLE);
				ibnPlace.setVisibility(View.VISIBLE);
				ibnHouse.setVisibility(View.VISIBLE);
				startGo();
			}
		});
		// ngung khao sat
		ibnPause.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				toggle.setVisibility(View.VISIBLE);
				MapCache.isStarting= false;
				if (ibnStart.getVisibility() == View.VISIBLE)
					return;
				// TODO Auto-generated method stub
				mLog.info("Button pause click");
				if (doAsynchronousTask != null) {
					doAsynchronousTask.cancel();
				}

				if (timer != null) {
					timer.cancel();
				}

				stopped = true;
				mHandler.removeCallbacksAndMessages(timerRunable);

				_glb.setFlag(0);
				_glb.setFlagMap(0);
				_glb.setTimeListId(null);
				ibnPause.setVisibility(View.GONE);
				ibnStart.setVisibility(View.VISIBLE);
				rootView.findViewById(R.id.header).setVisibility(
						LinearLayout.GONE);
				// mHandler1.removeCallbacks(startTimer);

				// check point count
				if (listPointOfCurrentRoad.size() > 1) {
					for (int i = 0; i < listPointOfCurrentRoad.size(); i++) {
						LatLng point = listPointOfCurrentRoad.get(i);
						db.insertPositionList(point.getLatitude() + "",
								point.getLongitude() + "", idTime);
					}
					//xóa đường bị phân mảnh
				/*	for (int i = listPointOfCurrentRoad.size() - 1; i < listPointOfCurrentRoad
							.size(); i--) {
						mapView.removeVector(lstcurrentdiscreteRoad.get(i));
						lstcurrentdiscreteRoad.remove(i);
					}
				
					// vẽ lại đường không bị phân mảnh
					currentRoad.addAll(listPointOfCurrentRoad)
					.strokeColor(Color.parseColor("#63D60A"))
					.strokeWidth(15);
					mapView.addPolyline(currentRoad);*/

					MapCache.lstPolylineOptions.add(currentRoad.clone());

				}

				listPointOfCurrentRoad.clear();
			}
		});

		// them cac diem ve road
		ibnRoad.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (MapCache.isToggle) {
					currentRoad = new PolylineOptions();
					listPointOfCurrentRoad = new ArrayList<LatLng>();
					mHeaderMode = HEADER_MODE_ROAD;
					ibnRoad.setVisibility(View.GONE);
					ibnRoad32.setVisibility(View.VISIBLE);
					ibnPoles32.setVisibility(View.GONE);
					ibnPlace32.setVisibility(View.GONE);
					ibnHouse32.setVisibility(View.GONE);
					ibnPlace.setVisibility(View.VISIBLE);
					ibnPoles.setVisibility(View.VISIBLE);
					ibnHouse.setVisibility(View.VISIBLE);
					toggle.setVisibility(View.GONE);
					Toast.makeText(getActivity(),
							"Chọn nhiều hơn 2 vị trí để thêm đường",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		ibnRoad32.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mHeaderMode = HEADER_MODE_ROAD32;
				try {
					ibnRoad.setVisibility(View.VISIBLE);
					ibnRoad32.setVisibility(View.GONE);
					toggle.setVisibility(View.VISIBLE);
					saveRoadToggleOn();
			} catch (Exception e) {
				e.printStackTrace();
				}
			}
		});
		
		// Them cot
		ibnPoles.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mHeaderMode==HEADER_MODE_ROAD){
					Toast.makeText(getActivity(), "Phải tắt vẽ đường trước", Toast.LENGTH_SHORT).show();
				}else{
					try {
						mLog.info("Button POLES click");
						if (!MapCache.isToggle)
							showPopupPoles();
						else {
							ibnPoles.setVisibility(View.GONE);
							ibnPoles32.setVisibility(View.VISIBLE);
							ibnRoad32.setVisibility(View.GONE);
							ibnPlace32.setVisibility(View.GONE);
							ibnHouse32.setVisibility(View.GONE);
							ibnRoad.setVisibility(View.VISIBLE);
							ibnPlace.setVisibility(View.VISIBLE);
							ibnHouse.setVisibility(View.VISIBLE);
							toggle.setVisibility(View.VISIBLE);
							
							//if(mHeaderMode== HEADER_MODE_ROAD) saveRoadToggleOn();
							mHeaderMode = HEADER_MODE_POLE;
							Toast.makeText(getActivity(), "Chọn vị trí thêm cột",
									Toast.LENGTH_SHORT).show();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		ibnPoles32.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mHeaderMode = HEADER_MODE_POLE32;
				// TODO Auto-generated method stub
				ibnPoles.setVisibility(View.VISIBLE);
				ibnPoles32.setVisibility(View.GONE);
				try {
					mLog.info("Button POLES click");
					Toast.makeText(getActivity(), "Đã tắt chức năng thêm cột",
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

		// them dia danh
		ibnPlace.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mHeaderMode==HEADER_MODE_ROAD){
					Toast.makeText(getActivity(), "Phải tắt vẽ đường trước", Toast.LENGTH_SHORT).show();
				}else{
				try {
					mLog.info("Button Place click");
					if (!MapCache.isToggle)
						showPopupPlace();
					else {
						ibnPlace32.setVisibility(View.VISIBLE);
						ibnPlace.setVisibility(View.GONE);
						ibnRoad32.setVisibility(View.GONE);
						ibnPoles32.setVisibility(View.GONE);
						ibnHouse32.setVisibility(View.GONE);
						ibnRoad.setVisibility(View.VISIBLE);
						ibnPoles.setVisibility(View.VISIBLE);
						ibnHouse.setVisibility(View.VISIBLE);
						toggle.setVisibility(View.VISIBLE);
						
					//	if(mHeaderMode== HEADER_MODE_ROAD) saveRoadToggleOn();
						mHeaderMode = HEADER_MODE_PLACE;
						Toast.makeText(getActivity(),
								"Chọn vị trí thêm địa danh", Toast.LENGTH_SHORT)
								.show();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
			}
		});
		ibnPlace32.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mHeaderMode = HEADER_MODE_PLACE32;
				ibnPlace.setVisibility(View.VISIBLE);
				ibnPlace32.setVisibility(View.GONE);

				try {
					mLog.info("Button Place click");
					Toast.makeText(getActivity(),
							"Đã tắt chức năng thêm địa danh",
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

		// them nha
		ibnHouse.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mHeaderMode==HEADER_MODE_ROAD){
					Toast.makeText(getActivity(), "Phải tắt vẽ đường trước", Toast.LENGTH_SHORT).show();
				}else{
				try {
					mLog.info("Button House click");
					// showPopupHouse();
					if (!MapCache.isToggle) {
						saveHouseToDB(gps.longitude, gps.latitude);
					} else {
						ibnHouse.setVisibility(View.GONE);
						ibnHouse32.setVisibility(View.VISIBLE);
						ibnPlace32.setVisibility(View.GONE);
						ibnPlace.setVisibility(View.VISIBLE);
						ibnRoad32.setVisibility(View.GONE);
						ibnPoles32.setVisibility(View.GONE);
						ibnRoad.setVisibility(View.VISIBLE);
						ibnPoles.setVisibility(View.VISIBLE);
						toggle.setVisibility(View.VISIBLE);
						
					//	if(mHeaderMode== HEADER_MODE_ROAD) saveRoadToggleOn();
						mHeaderMode = HEADER_MODE_HOUSE;
						Toast.makeText(getActivity(), "chọn vị trí thêm nhà",
								Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				}
			}
		});

		ibnHouse32.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mHeaderMode = HEADER_MODE_HOUSE32;
				// TODO Auto-generated method stub
				ibnHouse.setVisibility(View.VISIBLE);
				ibnHouse32.setVisibility(View.GONE);
				try {
					mLog.info("Button HOUSES click");
					Toast.makeText(getActivity(), "Đã tắt chức năng thêm nhà",
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		// Bat su kien click vao mot Marker  handle marker
		mapView.setMarkerClickListener(new MapLayer.OnClickListener() {
			@Override
			public boolean onClick(Point pt, LatLng latLng, MapObject mapObject) {
				Marker marker = (Marker) mapObject;
				currentMaker = marker;
				Log.e("zIndex", "zIndex: " + currentMaker.getZIndex());
				boolean isProcess = false;
				if ("Cột điện".equalsIgnoreCase(marker.getTitle())
						&& mHeaderMode != HEADER_MODE_POLE
						&& mHeaderMode != HEADER_MODE_ROAD
						&& mHeaderMode != HEADER_MODE_HOUSE
						&& mHeaderMode != HEADER_MODE_PLACE
						&& MapCache.isStarting != true) {
					isProcess = true;
					InfoWindowOptions infoWindowCustomize = new InfoWindowOptions(
							marker.getTitle(), marker.getPosition())
							.title("Cột điện")
							.snippet(
									db.getPoleCodeById(currentMaker.getZIndex()))
							.hyperlink("ChangeLocation", "Thay đổi vị trí")
							.hyperlink("Delete", "Xóa cột điện")
							.hyperlink("UpdateLocation","Cập nhật vị trí");
					mapView.showInfoWindow(infoWindowCustomize);
				} else if ("Nhà dân".equalsIgnoreCase(marker.getTitle())
						&& mHeaderMode != HEADER_MODE_POLE
						&& mHeaderMode != HEADER_MODE_ROAD
						&& mHeaderMode != HEADER_MODE_HOUSE
						&& mHeaderMode != HEADER_MODE_PLACE
						&& MapCache.isStarting != true) {
					isProcess = true;
					InfoWindowOptions infoWindowCustomize = new InfoWindowOptions(
							marker.getTitle(), marker.getPosition())
							.title("Nhà dân")
							.hyperlink("ChangeLocation", "Thay đổi vị trí")
							.hyperlink("Delete", "Xóa nhà dân")
							.hyperlink("UpdateLocation","Cập nhật vị trí ");
					mapView.showInfoWindow(infoWindowCustomize);
				} else if ("Địa danh".equalsIgnoreCase(marker.getTitle())
						&& mHeaderMode != HEADER_MODE_POLE
						&& mHeaderMode != HEADER_MODE_ROAD
						&& mHeaderMode != HEADER_MODE_HOUSE
						&& mHeaderMode != HEADER_MODE_PLACE
						&& MapCache.isStarting != true) {
					isProcess = true;
					InfoWindowOptions infoWindowCustomize = new InfoWindowOptions(
							marker.getTitle(), marker.getPosition())
							.title("Địa danh")
							.snippet(
									db.getPlaceNameById(currentMaker
											.getZIndex()))
							.hyperlink("ChangeLocation", "Thay đổi vị trí")
							.hyperlink("Delete", "Xóa địa danh")
							.hyperlink("UpdateLocation","Cập nhật vị trí ");
					mapView.showInfoWindow(infoWindowCustomize);
				} /*
				 * else if ("Địa danh".equalsIgnoreCase(marker.getTitle())) {
				 * isProcess = true; InfoWindowOptions infoWindowCustomize = new
				 * InfoWindowOptions( marker.getTitle(),
				 * marker.getPosition()).title( "diem").snippet(
				 * db.getPlaceNameById(currentMaker.getZIndex())) //
				 * .hyperlink("ChangeLocation", "Move") // .hyperlink("Delete",
				 * "Delete") ; mapView.showInfoWindow(infoWindowCustomize); }
				 */
				return isProcess;
			}
		});
		
		// Bat su kien kich vao link trong InfoBox
		mapView.setInfoWindowHyperlinkListener(new InfoBoxLayer.OnHyperlinkListener() {
			@Override
			public boolean onClick(InfoWindow infoWindow, String linkName) {

				if ("ChangeLocation".equalsIgnoreCase(linkName)) {
					Log.e("title", "title: " + currentMaker.getTitle());
					mapView.hideInfoWindow();
					// Drag & Drop
					if (currentMaker != null) {
						currentMaker.setDraggable(true);
						Toast.makeText(getActivity(),
								"Nhấn và giữ đối tượng để thay đổi vị trí",
								Toast.LENGTH_SHORT).show();
					}
				}else if("UpdateLocation".equalsIgnoreCase(linkName)){
					idUpdate = currentMaker.getZIndex();
					mapView.hideInfoWindow();
					 showPopupUpdate();
				}
				else if ("Delete".equalsIgnoreCase(linkName)) {
					Log.e("title", "title: " + currentMaker.getTitle());
					Log.i("zIndex", "zIndex: " + currentMaker.getZIndex());
					int id = currentMaker.getZIndex();
					int resutl = -1;
					mapView.hideInfoWindow();
					Log.e("anhpt677", "currentMaker.getZIndex()=="+currentMaker.getZIndex());
					
					
					if ("Cột điện".equalsIgnoreCase(currentMaker.getTitle())) {
						resutl = db.deleteTableById(id, "POLES_LIST");
						// update map cache
					//	Log.e("anhpt677", "id=====  "  +id);
						for (int i = 0; i < MapCache.listPole.size(); i++) {
							PoleForm poleFrm = MapCache.listPole.get(i);
							if (poleFrm.getIndex() == id) {
								MapCache.listPole.remove(i);
								break;
							}
						}
					} else if ("Nhà dân".equalsIgnoreCase(currentMaker
							.getTitle())) {
						Log.e("anhpt677", "id=====  "  +id);
						resutl = db.deleteTableById(id, "HOUSE_LIST");
						// update map cache
						for (int i = 0; i < MapCache.listHouse.size(); i++) {
							HouseForm houseFrm = MapCache.listHouse.get(i);
							if (houseFrm.getId() == id) {
								MapCache.listHouse.remove(i);
								break;
							}
						}
					} else if ("Địa danh".equalsIgnoreCase(currentMaker
							.getTitle())) {
						resutl = db.deleteTableById(id, "PLACE_LIST");
						// update map cache
						for (int i = 0; i < MapCache.listPosition.size(); i++) {
							PositionForm positionFrm = MapCache.listPosition
									.get(i);
							if (positionFrm.getId() == id) {
								MapCache.listPosition.remove(i);
								break;
							}
						}
					}
					if (resutl == 1) {
						mapView.removeMarker(currentMaker);
						// hideFunctionsButtons();

						mapView.refresh();
						currentMaker = null;
						Toast.makeText(getActivity(), "Đã xóa đối tượng",
								Toast.LENGTH_SHORT).show();
					}
				}

				return false;
			}
		});

		// Bat su kien move marker
		mapView.setMarkerDragListener(new MapLayer.OnDragListener() {
			@Override
			public boolean onDragStart(Point arg0, LatLng arg1,
					MapObject mapObject) {
				Toast.makeText(getActivity(),
						"Di chuyển đối tượng để thay đổi vị trí",
						Toast.LENGTH_SHORT).show();
				return false;
			}

			@Override
			public boolean onDragEnd(Point arg0, LatLng arg1,
					MapObject mapObject) {
				Marker marker = (Marker) mapObject;
				Log.e("title", "title: " + marker.getTitle());
				Log.i("zIndex", "zIndex: " + marker.getZIndex());
				int id = currentMaker.getZIndex();
				int resutl = -1;
				String latitude = String.valueOf(marker.getPosition()
						.getLatitude());
				String longitude = String.valueOf(marker.getPosition()
						.getLongitude());
				if ("Cột điện".equalsIgnoreCase(currentMaker.getTitle())) {
					db.updateObjectById(id, latitude, longitude, "POLES_LIST");
					// update cache position
					for (int i = 0; i < MapCache.listPole.size(); i++) {
						PoleForm poleFrm = MapCache.listPole.get(i);
						if (poleFrm.getIndex() == id) {
							poleFrm.setLat(Double.parseDouble(latitude));
							poleFrm.setLng(Double.parseDouble(longitude));
							break;
						}
					}
				} else if ("Nhà dân".equalsIgnoreCase(currentMaker.getTitle())) {
					db.updateObjectById(id, latitude, longitude, "HOUSE_LIST");
					// update cache position
					for (int i = 0; i < MapCache.listHouse.size(); i++) {
						HouseForm houseFrm = MapCache.listHouse.get(i);
						if (houseFrm.getId() == id) {
							houseFrm.setPoint(new LatLng(Double
									.parseDouble(latitude), (Double
									.parseDouble(longitude))));
							break;
						}
					}
				} else if ("Địa danh".equalsIgnoreCase(currentMaker.getTitle())) {
					db.updateObjectById(id, latitude, longitude, "PLACE_LIST");
					// update cache position
					for (int i = 0; i < MapCache.listPosition.size(); i++) {
						PositionForm positionFrm = MapCache.listPosition.get(i);
						if (positionFrm.getId() == id) {
							positionFrm.setPoint(new LatLng(Double
									.parseDouble(latitude), (Double
									.parseDouble(longitude))));
							break;
						}
					}
				}
				// if()
				Toast.makeText(getActivity(), "Cập nhật vị trí thành công",
						Toast.LENGTH_SHORT).show();
				marker.setDraggable(false);
				return false;
			}

			@Override
			public boolean onDrag(Point arg0, LatLng arg1, MapObject mapObject) {

				return false;
			}
		});

		//
		ibnSwitch1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mHeaderMode==HEADER_MODE_ROAD){
					Toast.makeText(getActivity(), "Phải tắt vẽ đường trước", Toast.LENGTH_SHORT).show();
				}else{
					checkSwitch = true;
					ibnSwitch1.setVisibility(View.GONE);
					ibnSwitch2.setVisibility(View.VISIBLE);
					ReloadMapFromCache(checkSwitch);
				}
			}
		});

		ibnSwitch2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				checkSwitch = false;
				ibnSwitch1.setVisibility(View.VISIBLE);
				ibnSwitch2.setVisibility(View.GONE);
				ReloadMapFromCache(checkSwitch);
			}
		});

		// tat ve duong
		ibnRawLine1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				rawLine = false;
				ibnRawLine1.setVisibility(View.GONE);
				ibnRawLine2.setVisibility(View.VISIBLE);

				// Xoa cache va luu vao DB
				if (listPointOfCurrentRoad.size() > 1) {
					for (int i = 0; i < listPointOfCurrentRoad.size(); i++) {
						LatLng point = listPointOfCurrentRoad.get(i);
						db.insertPositionList(point.getLatitude() + "",
								point.getLongitude() + "", idTime);
					}
					
				/*	//xóa đường bị phân mảnh
					for (int i = listPointOfCurrentRoad.size() - 1; i < listPointOfCurrentRoad
							.size(); i--) {
						mapView.removeVector(lstcurrentdiscreteRoad.get(i));
						lstcurrentdiscreteRoad.remove(i);
					}
				
					// vẽ lại đường không bị phân mảnh
					currentRoad.addAll(listPointOfCurrentRoad)
					.strokeColor(Color.parseColor("#63D60A"))
					.strokeWidth(15);
					mapView.addPolyline(currentRoad);*/
					
					// duplicate line & set lai idTime
					idTime = (int) db.dupplicateExistRoad(idTime);
					// save đường này vào danh sách các đường.
					MapCache.lstPolylineOptions.add(currentRoad.clone());
					// reset
					listPointOfCurrentRoad.clear();

				}

				Toast.makeText(getActivity(), "Chức năng vẽ đường đã được tắt",
						Toast.LENGTH_SHORT).show();
			}
		});

		// bat ve duong
		ibnRawLine2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				rawLine = true;
				ibnRawLine1.setVisibility(View.VISIBLE);
				ibnRawLine2.setVisibility(View.GONE);
				currentRoad = new PolylineOptions();
				listPointOfCurrentRoad = new ArrayList<LatLng>();
				Toast.makeText(getActivity(), "Chức năng vẽ đường đã được bật",
						Toast.LENGTH_SHORT).show();
			}
		});
		
		
		
		// anhpt edit. handle toggle button tren layout
		toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				MapCache.isToggle = toggle.isChecked();
				if (isChecked) {
					_glb.setTimeListId(null);
				//	MapCache.isStarting= true;
					Toast.makeText(getActivity(),
							"Bạn vừa tắt vẽ GPS để để bật vẽ tay",
							Toast.LENGTH_SHORT).show();
					if (gps.latitude == Double.parseDouble("0.0")
							|| gps.longitude == Double.parseDouble("0.0")) {
						Toast.makeText(getActivity(), "Không lấy được tọa độ",
								Toast.LENGTH_SHORT).show();
					} else {
						showFunctionsButtons();
						mHeaderMode = 30;
						ibnRawLine1.setVisibility(View.GONE);
						ibnRawLine2.setVisibility(View.GONE);
						txtViewBottom.setVisibility(View.GONE);

				}
				}
				 else {
					// The toggle is disabled
					//MapCache.isStarting= false;
					_glb.setTimeListId(null);
					Toast.makeText(getActivity(), "Bạn vừa tắt vẽ tay để bật vẽ GPS", Toast.LENGTH_SHORT).show();
					ibnRawLine2.setVisibility(View.VISIBLE);
					ibnRoad.setVisibility(View.INVISIBLE);
					txtViewBottom.setVisibility(View.VISIBLE);
					rootView.findViewById(R.id.header).setVisibility(
							View.INVISIBLE);
					ibnStart.setVisibility(View.VISIBLE);
					if (mHeaderMode == HEADER_MODE_ROAD) {
						ibnRoad.setVisibility(View.VISIBLE);
						ibnRoad32.setVisibility(View.GONE);
					//	toggle.setEnabled(false);
					//	saveRoadToggleOn();
						mHeaderMode = 30;
					}
					if (mHeaderMode == HEADER_MODE_HOUSE) {
						ibnHouse32.setVisibility(View.GONE);
						ibnHouse.setVisibility(View.VISIBLE);
					}
					if (mHeaderMode == HEADER_MODE_POLE) {
						ibnPoles.setVisibility(View.VISIBLE);
						ibnPoles32.setVisibility(View.GONE);
					}
					if (mHeaderMode == HEADER_MODE_PLACE) {
						ibnPlace.setVisibility(View.VISIBLE);
						ibnPlace32.setVisibility(View.GONE);
					}
					mHeaderMode = 30;
				}
			}
			
		});
		
	
		
		//  anhpt edit.  Bat su kien click vao mot doi tuong duong là vector polyline(mapview.polylineoption())
		//  Xóa đường
		
		mapView.setVectorClickListener(new MapLayer.OnClickListener() {
			@Override
			public boolean onClick(Point pt, LatLng latLng, MapObject mapObject) {
				// Su kien kich vao polyline
				Polyline polyline = (Polyline) mapObject;
				currentPolyline = polyline;
				currentPolyline.getPoints();
				Log.e("test", "MapCache.lstPolylineOptions.size="+MapCache.lstPolylineOptions.size());
			// nếu đang vẽ thì k được xóa 
				if ((mHeaderMode == HEADER_MODE_ROAD
						|| mHeaderMode == HEADER_MODE_POLE
						|| mHeaderMode == HEADER_MODE_ROAD
						|| mHeaderMode == HEADER_MODE_HOUSE
						|| mHeaderMode == HEADER_MODE_PLACE)
						|| MapCache.isStarting == true ){
								
				}
				else{
						AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
								getActivity());
						myAlertDialog.setTitle("Thông báo");
						myAlertDialog.setMessage("Bạn có muốn xóa đường");
						myAlertDialog.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Do something here where "ok" clicked
										//for (int i = 0; i<MapCache.lstPolylineOptions.size(); i++){
											
										//}
										try {
											for (int i = 0; i < currentPolyline.getPoints()
													.size(); i++) {
												// xóa polyline trong db mà vừa chạm vào
												//currentRoad.getPoints().remove(i);
												int a= db.detelePointByLatLng(Double
														.toString(currentPolyline
																.getPoints().get(i)
																.getLatitude()));
												//Log.e("anhpt67", "a=======" +a );
												/////db.deleteListTimeStopByid(a);
												
												
												//xóa polyline trong cache mà vừa chạm vào
												for (int j = 0; j < MapCache.lstPolylineOptions
														.size(); j++) {
													PolylineOptions object = MapCache.lstPolylineOptions
															.get(j);
													for (int k = 0; k < object
															.getPoints().size(); k++)
														if (object.getPoints().size() == currentPolyline
																.getPoints().size()
																&& object.getPoints()
																		.get(k)
																		.getLatitude() == currentPolyline
																		.getPoints()
																		.get(i)
																		.getLatitude())
															MapCache.lstPolylineOptions
																	.remove(j);
												}
												
											}
										}catch(NullPointerException e){
											e.printStackTrace();
											// TODO: handle exception
											AlertDialog.Builder myAlertDialog  =  new AlertDialog.Builder(getActivity());              
											myAlertDialog.setTitle("Thông báo");
											myAlertDialog.setMessage("Bạn đã chạm vào nhiều hơn một đường không thể xóa nhiều đường");
											myAlertDialog.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
												public void onClick(DialogInterface dialog,
														int whichButton) {
													return;
													}
												});
											
										
										}
										
										currentPolyline.getZIndex();
										Log.e("anhpt67", "currentPolyline.getZIndex()====" +currentPolyline.getZIndex());
										Log.e("anhpt67", "MapCache.lstPolylineOptions.size()" +MapCache.lstPolylineOptions.size());
										mapView.removeVector(currentPolyline);
										currentPolyline.remove();
										mapView.refresh();
										Toast.makeText(getActivity(),
												"Xóa đường thành công",
												Toast.LENGTH_SHORT).show();
										// isProcess = true;
										dialogShown = false;

									}
								});

						myAlertDialog.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// So sth here when "cancel" clicked.
										dialogShown = false;
									}
								});
						
						if (dialogShown){
							
						} else {
							myAlertDialog.show();
							dialogShown = true;
						}
				}
				return false;
			}
		});
		
		// anhpt edit. touch vao map
		mapView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return mapTouched(event);
			}
		});
		// refresh
		ReloadMapFromCache(checkSwitch);
		return rootView;
	} 

	//////////////////////////////////////////////////////////////////////////////////////////
	int temp=0;
	
	// anhpt edit lay toa do khi touch map
	protected boolean mapTouched(MotionEvent event) {
		if (MapCache.isToggle && event.getAction() == MotionEvent.ACTION_UP) {
			int x = (int) event.getX();
			int y = (int) event.getY();
			geoPoint = mapView.getProjection().fromOriginalViewPixel(x, y);
			lat = geoPoint.getLatitude();
			lon = geoPoint.getLongitude();
			
			Log.e("lat touch", String.valueOf(lat));
			Log.e("lng touch", String.valueOf(lon));
			Log.e("CalDistance",
					String.valueOf(CalDistance(lat, lon, gps.getLatitude(),
							gps.getLongitude())));
			
			
		//	Toast.makeText(getActivity(), "temp="+temp, Toast.LENGTH_SHORT).show();
			
			if (mHeaderMode == HEADER_MODE_ROAD) {
				mapView.setCenter(geoPoint);
				temp++;
				try {
					MarkerOptions opts1 = new MarkerOptions()
							.position(new LatLng(lat, lon));
					/*if(listPointOfCurrentRoad.isEmpty()){
						opts1.getIcon();
						mapView.addMarker(opts1);
					}*/
					// list các điểm chạm vào bản đồ để vẽ đường cho đến khi kết thúc (save đường).
					listPointOfCurrentRoad.add(opts1.getPosition().clone()); 
					Log.e("Anhpt67", "listPointOfCurrentRoad.size()="+listPointOfCurrentRoad.size());
					currentRoad.add(opts1.getPosition())
							.strokeColor(Color.parseColor("#63D60A"))
							.strokeWidth(15);
					
					
					//listPointOfCurrentRoad_.add(opts1.getPosition());
					//listMarkerDrawRoad.add(mapView.addMarker(opts1));
				/*	if(temp % 2 ==1){
						listPointOfCurrentRoad_.remove(temp);
						//listMarkerDrawRoad.remove(temp);
					//	mapView.removeMarker(listMarkerDrawRoad.get(temp));
						//mapView.refresh();
						
					}*/
					
					
					// listpoinofcurrentroad vaf lstcurrentRoad giong nhau. khác nhau ở chỗ 1 cái 
					// là list cac điểm kiểu polyline() 1 cái là kiểu polylineoption()
					lstcurrentdiscreteRoad.add(mapView.addPolyline(currentRoad.clone()));////<------Note
				//	MapCache.lstPolylineOptions.add(currentRoad.clone());
					Log.e("anhpt67", "lstPolylineOptions===" + MapCache.lstPolylineOptions.get(1) );
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			if (CalDistance(lat, lon, gps.getLatitude(), gps.getLongitude()) <= Config.maximumDistancePoint) {

				if (mHeaderMode == HEADER_MODE_POLE) {
					// / fix lỗi k để popupwindow chồng lên nhau k bấm được
					if (PopupWindowPole != null && PopupWindowPole.isShowing()) {
						PopupWindowPole.dismiss();
					} else {
						showPopupPoles();
					}

				}
				if (mHeaderMode == HEADER_MODE_PLACE) {
					if (PopupWindowPlace != null
							&& PopupWindowPlace.isShowing()) {
						PopupWindowPlace.dismiss();
					} else {
						showPopupPlace();
					}
				}
				if (mHeaderMode == HEADER_MODE_HOUSE) {
					saveHouseToDB(lon, lat);
				}

				Log.i(TAG, geoPoint.toString());
				// Neu tro vao button de ve thi moi toast canh bao
		}
			else if (mHeaderMode == HEADER_MODE_HOUSE
				|| mHeaderMode == HEADER_MODE_PLACE
				|| mHeaderMode == HEADER_MODE_POLE) {
			Toast.makeText(
					getActivity(),
				"Vẽ vượt phạm vi cho phép ( Khoảng cách 1000m từ vị trí GPS đến điểm vẽ)",
				Toast.LENGTH_SHORT).show();
	}

		}
		return false;

	}
	
	
	// anhpt edit save đường
	
	private void saveRoadToggleOn() {
		// save road
		temp=0;
		Toast.makeText(getActivity(),
				"Đã tắt chức năng thêm đường và save vào database",
				Toast.LENGTH_SHORT).show();
		
		if (_glb.getTimeListId() == null) {
			mLog.info("Insert new Track");
			idTime = (int) db.insertRoad("0", "0", null, null);
		}
		// save đường vào database
		if(listPointOfCurrentRoad.size() >1)  //nếu chấm 1 điểm thì không save vào database
		for (int i = 0; i < listPointOfCurrentRoad.size(); i++) {
			LatLng point = listPointOfCurrentRoad.get(i);
			db.insertPositionList(point.getLatitude() + "",
					point.getLongitude() + "", idTime);
		}

		// vẽ một đoạn đường mới không bị phân mảnh
		if (!MapCache.isToggle) {
		} else {
			currentRoad = new PolylineOptions()
					.addAll(listPointOfCurrentRoad)
					.strokeColor(Color.parseColor("#63D60A")).strokeWidth(15);
			mapView.addPolyline(currentRoad);
			// add đường không bị phân mảnh vào trong cache
			MapCache.lstPolylineOptions.add(currentRoad.clone());

			// Xóa đường cũ bị phân mảnh
			for (int i = listPointOfCurrentRoad.size() - 1; i < listPointOfCurrentRoad
					.size(); i--) {
				mapView.removeVector(lstcurrentdiscreteRoad.get(i));
				lstcurrentdiscreteRoad.remove(i);
			}
		}
		lstcurrentdiscreteRoad.clear();
		// MapCache.lstPolylineOptions.clear();
		// duplicate line & set lai idTime
		// idTime = (int) db.dupplicateExistRoad(idTime);
		
		// MapCache.lstPolylineOptions.add(polylineoption.clone());

		// listPointOfCurrentRoad.
		listPointOfCurrentRoad.clear();
		// reset
		mapView.refresh();
		// MapCache.lstPolylineOptions.add(currentRoad.clone());
		// currentRoad.visible(false);
		// mapView.addPolyline(currentRoad.clone());
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.date_picker, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// same as using a normal menu
		switch (item.getItemId()) {

		case R.id.chooseDate:
			if (MapCache.isToggle) {
				if (mHeaderMode == HEADER_MODE_PLACE)
					Toast.makeText(getActivity(),
							"Dừng vẽ địa danh để xem dữ liệu lịch sử",
							Toast.LENGTH_SHORT).show();
				else if (mHeaderMode == HEADER_MODE_ROAD)
					Toast.makeText(getActivity(),
							"Dừng vẽ đường để xem dữ liệu lịch sử",
							Toast.LENGTH_SHORT).show();
				else if (mHeaderMode == HEADER_MODE_HOUSE)
					Toast.makeText(getActivity(),
							"Dừng vẽ nhà để xem dữ liệu lịch sử",
							Toast.LENGTH_SHORT).show();
				else if (mHeaderMode == HEADER_MODE_POLE)
					Toast.makeText(getActivity(),
							"Dừng vẽ cột để xem dữ liệu lịch sử",
							Toast.LENGTH_SHORT).show();
				else
					showSelectionDatePopup();

			} else {
				if (stopped) {
					showSelectionDatePopup();
				} else {
					Toast.makeText(getActivity(),
							"Dừng khảo sát để xem dữ liệu lịch sử.",
							Toast.LENGTH_SHORT).show();
				}

			}
			break;
		}
		return true;

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (gps == null) {
			gps = new GPSTracker(getActivity());
		}
		if (mapView != null)
			if (stopped == false) {
				rootView.findViewById(R.id.header).setVisibility(View.VISIBLE);
				ibnStart.setVisibility(View.GONE);
				ibnPause.setVisibility(View.VISIBLE);
				if (_glb.getTimeListId() != null) {

					List<InfomationForm> lstPosition = db
							.getPositionByTime(_glb.getTimeListId());
					Log.e("count", String.valueOf(lstPosition.size()));
					if (lstPosition.size() > 0) {
						for (InfomationForm obj : lstPosition) {
							currentRoad
									.add(new LatLng(Double.parseDouble(obj
											.getLatitude()), Double
											.parseDouble(obj.getLongtitude())))
									.strokeColor(Color.parseColor("#63D60A"))
									.strokeWidth((15));
							mapView.addPolyline(currentRoad);
						}
					}

					List<InfomationForm> lstHouse = db.getHouseByTime(_glb
							.getTimeListId());
					Log.e("count", String.valueOf(lstHouse.size()));
					if (lstHouse.size() > 0) {
						for (InfomationForm obj : lstHouse) {
							MarkerOptions opts1 = new MarkerOptions()
									.position(
											new LatLng(Double.parseDouble(obj
													.getLatitude()), Double
													.parseDouble(obj
															.getLongtitude())))
									.title("Nhà dân")
									.icon(BitmapFactory
											.decodeResource(
													getResources(),
													checkSwitch ? R.drawable.house_finger_larger
															: R.drawable.house_24))
									.rotation(0);
							mapView.addMarker(opts1);
						}
					}

					List<InfomationForm> lstPlace = db.getPlaceByTime(_glb
							.getTimeListId());
					Log.e("count", String.valueOf(lstPlace.size()));
					if (lstPlace.size() > 0) {
						for (InfomationForm obj : lstPlace) {
							MarkerOptions opts1 = new MarkerOptions()
									.position(
											new LatLng(Double.parseDouble(obj
													.getLatitude()), Double
													.parseDouble(obj
															.getLongtitude())))
									.title("Địa danh")
									.icon(BitmapFactory
											.decodeResource(
													getResources(),
													checkSwitch ? R.drawable.place_icon_larger
															: R.drawable.place_24))
									.rotation(0);
							mapView.addMarker(opts1);
						}
					}
				}
			}
		mapView.refresh();
	}

	@Override
	public void onDestroy() {
		if (mapView != null) {
			mapView.destroy();
			mapView = null;
		}
		super.onDestroy();
	}

	// tu dong ve duong khi khao sat
	private Runnable timerRunable = new Runnable() {
		private LatLng mapPointLast = null;

		@SuppressWarnings("unchecked")
		public void run() {
			try {
				boolean refreshView = true;// refresh map view
				double latitude = gps.latitude;
				double longitude = gps.longitude;
				if (latitude == Double.parseDouble("0.0")
						|| longitude == Double.parseDouble("0.0")) {
					Toast.makeText(getActivity(), "Không lấy được tọa độ",
							Toast.LENGTH_SHORT).show();
					if (timer != null) {
						timer.cancel();
					}
					_glb.setFlag(0);
					_glb.setFlagMap(0);
					_glb.setTimeListId(null);
					ibnPause.setVisibility(View.GONE);
					ibnStart.setVisibility(View.VISIBLE);
					toggle.setVisibility(View.VISIBLE);
					rootView.findViewById(R.id.header).setVisibility(
							LinearLayout.GONE);
					// mHandler1.removeCallbacks(startTimer);
					stopped = true;
				} else {

					if (stopped) {
						mHandler.postDelayed(timerRunable, REFRESH_RATE);
					} else {
						elapsedTime = System.currentTimeMillis() - startTime;
						updateTimer(elapsedTime);
						mapView.setCenter(new LatLng(latitude, longitude),
								false);
						mapView.setZoom(mapView.getZoom(), false);
					}

				}

				if (rawLine) {
					currentRoad = new PolylineOptions();///// laáy trên ibnStart
					currentRoad.strokeWidth(15);///////
					LatLng mapPoint = new LatLng(latitude, longitude);
					// Lay diem cuoi sau khi ngat ve duong la diem dau tien cua
					// list moi
					if (listPointOfCurrentRoad.size() == 0) {
						if (mapPointLast != null) {
						//	mapPointLast= new LatLng (mapPointLast.getLatitude()+0.000000000000001, mapPointLast.getLongitude()+0.000000000000001);
						//	mapPointLast= new LatLng (mapPointLast.getLatitude(), mapPointLast.getLongitude());
							_glb.setCurrentComparePoint(mapPointLast);
							listPointOfCurrentRoad.add(mapPointLast.clone());
							currentRoad.add(mapPointLast)
									.strokeColor(Color.parseColor("#63D60A"))
									.strokeWidth(15);
							mapPointLast = null;
						//	lstcurrentdiscreteRoad.add(mapView.addPolyline(currentRoad.clone()));
						} else {
							_glb.setCurrentComparePoint(mapPoint);
							listPointOfCurrentRoad.add(mapPoint.clone());
							currentRoad.add(mapPoint)
									.strokeColor(Color.parseColor("#63D60A"))
									.strokeWidth(15);
						//	lstcurrentdiscreteRoad.add(mapView.addPolyline(currentRoad.clone()));
						}

					} else {

						double distance = CalDistance(mapPoint.getLatitude(),
								mapPoint.getLongitude(),
								_glb.getCurrentComparePoint().getLatitude(),
								_glb.getCurrentComparePoint().getLongitude());
						// check khoang cach de them diem
						if (distance > Config.minimumPointDistance) {
							if (listPointOfCurrentRoad.size() == 1) {
								_glb.setCachePoint(mapPoint);
								listPointOfCurrentRoad.add(mapPoint.clone());
								currentRoad
										.add(new LatLng(latitude, longitude))
										.strokeColor(
												Color.parseColor("#63D60A"))
										.strokeWidth(15);
								// set cache angle
								_glb.setCacheAngle(MapFunction.getLineAngle(
										_glb.getCurrentComparePoint(), mapPoint));
						//		lstcurrentdiscreteRoad.add(mapView.addPolyline(currentRoad.clone()));

							} else {
								listPointOfCurrentRoad.add(mapPoint.clone());
								currentRoad
										.add(new LatLng(latitude, longitude))
										.strokeColor(
												Color.parseColor("#63D60A"))
										.strokeWidth(15);
						//		lstcurrentdiscreteRoad.add(mapView.addPolyline(currentRoad.clone()));
							}
						} else {
							refreshView = false;
						}
					}
					// Kiem tra so luong diem de insert vao db
					if (listPointOfCurrentRoad.size() >= Config.maximumPointCount) {
						// diem cuoi = mapPoint -->luu ra cache
						for (int i = 0; i < listPointOfCurrentRoad.size(); i++) {
							LatLng point = listPointOfCurrentRoad.get(i);
							if (i == (listPointOfCurrentRoad.size() - 1)) {
								mapPointLast = point;
							}
							db.insertPositionList(point.getLatitude() + "",
									point.getLongitude() + "", idTime);
						}
						
						/*//xóa đường bị phân mảnh
						for (int i = listPointOfCurrentRoad.size() - 1; i < listPointOfCurrentRoad
								.size(); i--) {
							mapView.removeVector(lstcurrentdiscreteRoad.get(i));
							lstcurrentdiscreteRoad.remove(i);
						}
					
						// vẽ lại đường không bị phân mảnh
						currentRoad= new PolylineOptions().addAll(listPointOfCurrentRoad)
						.strokeColor(Color.parseColor("#63D60A"))
						.strokeWidth(15);
						mapView.addPolyline(currentRoad);*/
						
						
						
						// duplicate line & set lai idTime
						idTime = (int) db.dupplicateExistRoad(idTime);

						MapCache.lstPolylineOptions.add(currentRoad.clone());
						// reset
						listPointOfCurrentRoad.clear();

					}
				}

				// refresh view
				if (refreshView) {
					ReloadMapFromCache(checkSwitch);
					refreshView = false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	private RadioButton rdoVuongdon;
	private RadioButton rdoVuongdoi;
	private RadioButton rdoTrondon;
	private RadioButton rdoTrondoi;
	private RadioButton rdoCotthep;
	private RadioButton rdoCotgo;
	private RadioButton rdoViettel;
	private RadioButton rdoVNPT;
	private RadioButton rdoDienluc;
	private RadioButton rdoXa;
	private EditText edtDoCaoThietBi;
	private RadioButton rdbTruoc;
	private RadioButton rdbSau;
	private RadioButton rdbTrai;
	private RadioButton rdbPhai;
	private RadioButton rdbKhongCo;
	

	private void updateTimer(float time) {
		secs = (long) (time / 1000);
		mins = (long) ((time / 1000) / 60);
		hrs = (long) (((time / 1000) / 60) / 60);
		secs = secs % 60;
		seconds = String.valueOf(secs);
		if (secs == 0) {
			seconds = "00";
		}
		if (secs < 10 && secs > 0) {
			seconds = "0" + seconds;
		}
		/* Convert the minutes to String and format the String */
		mins = mins % 60;
		minutes = String.valueOf(mins);
		if (mins == 0) {
			minutes = "00";
		}
		if (mins < 10 && mins > 0) {
			minutes = "0" + minutes;
		} /* Convert the hours to String and format the String */
		hours = String.valueOf(hrs);
		if (hrs == 0) {
			hours = "00";
		}
		if (hrs < 10 && hrs > 0) {
			hours = "0" + hours;
		}
		txtViewBottom.setText(hours + ":" + minutes + ":" + seconds);
	}

	/*
	 * start khao sat
	 */

	private void startGo() {
		stopped = false;
		double latitude = gps.latitude;
		double longitude = gps.longitude;
		if (latitude == Double.parseDouble("0.0")
				|| longitude == Double.parseDouble("0.0")) {
			Toast.makeText(getActivity(), "Không lấy được tọa độ",
					Toast.LENGTH_SHORT).show();
			mLog.info("Can't get position");
			_glb.setFlag(0);
			_glb.setFlagMap(0);
			_glb.setTimeListId(null);
			toggle.setVisibility(View.VISIBLE);
			ibnPause.setVisibility(View.GONE);
			ibnStart.setVisibility(View.VISIBLE);
			rootView.findViewById(R.id.header).setVisibility(LinearLayout.GONE);
			stopped = true;
			return;
		}
		rootView.findViewById(R.id.header).setVisibility(View.VISIBLE);
			txtViewBottom.setText("00:00:00");
			startTime = System.currentTimeMillis();
		
			
		//	if(rawLine){
				
				listPointOfCurrentRoad.clear();
				if (_glb.getTimeListId() == null) {
					mLog.info("Insert new Track");
					idTime = (int) db.insertRoad("0", "0", null, null);
				} else {
					mLog.info("get Old track");
					idTime = _glb.getTimeListId();
					if (db.getRoadPointCount(idTime, getActivity()) >= 2) {
						// duplicate line & set lai idTime
						idTime = (int) db.dupplicateExistRoad(idTime);
					}
				}
				if (gps.canGetLocation()) {
					timer = new Timer();

					doAsynchronousTask = new TimerTask() {
						@Override
						public void run() {
							mHandler.post(timerRunable);

						}
					};

					timer.schedule(doAsynchronousTask, 0, 1000);

				} else {
					gps.showSettingsAlert();
				}
	//		}

	}
	

	// ve lai map theo icon
	private void ReloadMapFromCache(boolean checkSwitch) {

		mapView.clear();
		// ve cac duong cu
		for (int i = 0; i < MapCache.lstPolylineOptions.size(); i++) {
			PolylineOptions polylineOption = MapCache.lstPolylineOptions.get(i);
			mapView.addPolyline(polylineOption.clone());
		}
/*		if(!MapCache.isToggle)
			// ve duong hien tai
			mapView.addPolyline(currentRoad.clone());*/
			
			
		// ve duong hien tai
	//	mapView.addPolyline(polylineoption.clone());

		// ve lai nha, cot, dia danh
		for (int i = 0; i < MapCache.listPole.size(); i++) {
			PoleForm poleFrm = MapCache.listPole.get(i);
			MarkerOptions mpole = new MarkerOptions()
					.position(new LatLng(poleFrm.getLat(), poleFrm.getLng()))
					.title("Cột điện")
					.zIndex(poleFrm.getIndex())
					.icon(BitmapFactory.decodeResource(getResources(),
							checkSwitch ? R.drawable.electricity_icon_larger
									: R.drawable.pole_24)).rotation(0);
			mapView.addMarker(mpole);
			if (mapView.getZoom()>2) mapView.addMarker(mpole).setVisible(false);
		}

		for (int i = 0; i < MapCache.listHouse.size(); i++) {
			HouseForm houseFrm = MapCache.listHouse.get(i);
			MarkerOptions mhouse = new MarkerOptions()
					.position(houseFrm.getPoint())
					.title("Nhà dân")
					.zIndex(houseFrm.getId())
					.icon(BitmapFactory.decodeResource(getResources(),
							checkSwitch ? R.drawable.house_finger_larger
									: R.drawable.house_24)).rotation(0);
			mapView.addMarker(mhouse);
		}

		for (int i = 0; i < MapCache.listPosition.size(); i++) {
			PositionForm positionFrm = MapCache.listPosition.get(i);
			MarkerOptions mposition = new MarkerOptions()
					.position(positionFrm.getPoint())
					.title("Địa danh")
					.zIndex(positionFrm.getId())
					.icon(BitmapFactory.decodeResource(getResources(),
							checkSwitch ? R.drawable.place_icon_larger
									: R.drawable.place_24)).rotation(0);
			mapView.addMarker(mposition);
		}
		mapView.refresh();

	}

	/*
	 * cap nhat dia danh anhpt edit
	 */
	private void showPopupPlace() {
		LayoutInflater layoutInflater = (LayoutInflater) getActivity()
				.getBaseContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);

		popupViewPlaces = layoutInflater.inflate(
				R.layout.activity_insert_place, null);
		btnInsert = (Button) popupViewPlaces.findViewById(R.id.btnInsert);
		btnCancelPlace = (Button) popupViewPlaces
				.findViewById(R.id.btnCancelPlace);
		edtPlaceName = (EditText) popupViewPlaces
				.findViewById(R.id.edtPlaceName);
		edtPlaceDescription = (EditText) popupViewPlaces
				.findViewById(R.id.edtPlaceDescription);
		PopupWindowPlace = new PopupWindow(popupViewPlaces,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		PopupWindowPlace.showAtLocation(popupViewPlaces, Gravity.CENTER, 0, 0);
		PopupWindowPlace.setFocusable(true);
		PopupWindowPlace.update();
		btnCancelPlace.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				PopupWindowPlace.dismiss();
			}
		});
		btnInsert.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (MapCache.isToggle) {
					savePlaceToDB(lon, lat);
				} else {
					if (gps.canGetLocation()) {
						savePlaceToDB(gps.longitude, gps.latitude);
					} else {
						gps.showSettingsAlert();
					}
				}
			}
		});
	}

	private void savePlaceToDB(double longitude, double latitude) {

		// TODO Auto-generated method stub
		String placeName = edtPlaceName.getText().toString().trim();
		String placeNote = edtPlaceDescription.getText().toString().trim();
		int id;
		if (placeName.length() > 0) {

			// double latitude= gps.Latitude;
			// double longitude = gps.Longitude;
			if ((id = db.insertPlaceList(String.valueOf(latitude),
					String.valueOf(longitude), placeName, placeNote, idTime)) != -1) {
				// map cache
				PositionForm positionFrm = new PositionForm();
				positionFrm.setId(id);
				positionFrm.setPoint(new LatLng(latitude, longitude));
				positionFrm.setPlaceName(placeName);
				positionFrm.setPlaceNote(placeNote);
				MapCache.listPosition.add(positionFrm);

				Log.e("insertPlace", "success. ID_KEY = " + id);
				MarkerOptions opts1 = new MarkerOptions()
						.position(new LatLng(latitude, longitude))
						.title("Địa danh")
						.zIndex(id)
						.icon(BitmapFactory.decodeResource(getResources(),
								checkSwitch ? R.drawable.place_icon_larger
										: R.drawable.place_24)).rotation(0);
				mapView.addMarker(opts1);
				Toast.makeText(getActivity(), "Thêm địa danh thành công",
						Toast.LENGTH_SHORT).show();
				PopupWindowPlace.dismiss();
				mapView.refresh();
			} else {
				Log.e("insertPlace", "fail");
				PopupWindowPlace.dismiss();
			}

		} else {
			createDialogValidate(Constant.MESSAGE_STR.PLACE_ISREQUIED).show();
		}

	}

	private void saveHouseToDB(double longitude, double latitude) {
		LatLng mapPoint = new LatLng(latitude, longitude);

		int id = db.insertHouseList(String.valueOf(mapPoint.getLatitude()),
				String.valueOf(mapPoint.getLongitude()), 0, 2);

		MarkerOptions mhouse = new MarkerOptions()
				.position(mapPoint)
				.title("Nhà dân")
				.zIndex(id)
				.icon(BitmapFactory.decodeResource(getResources(),
						checkSwitch ? R.drawable.house_finger_larger
								: R.drawable.house_24)).rotation(0);
		mapView.addMarker(mhouse);

		HouseForm info = new HouseForm();
		info.setPoint(mapPoint);
		info.setId(id);
		MapCache.listHouse.add(info);
		mapView.refresh();
		Toast.makeText(getActivity(), "Đã thêm nhà dân ", Toast.LENGTH_SHORT)
				.show();
	}
	
//anhpt67 edit: popup update location cho doi tuong:
	private void showPopupUpdate(){
		LayoutInflater layoutInflater = (LayoutInflater) getActivity()
				.getBaseContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);
		popupViewUpdate = layoutInflater.inflate(R.layout.activity_updatelocation,
				null);
	//	DisplayMetrics displaymetrics= new DisplayMetrics();
	//	getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
	//	int width = displaymetrics.widthPixels / 10;
		//TableRow.LayoutParams params1 = new TableRow.LayoutParams(width * 4,
			//	TableRow.LayoutParams.WRAP_CONTENT);
		
		edtKinhdo = (EditText) popupViewUpdate.findViewById(R.id.edtKinhdo);
		edtVido = (EditText) popupViewUpdate.findViewById(R.id.edtVido);
		
		btnSave =(Button) popupViewUpdate.findViewById(R.id.btnSave);
		btnExit = (Button) popupViewUpdate.findViewById(R.id.btnExit);

		// edtKinhdoUpdate.setLayoutParams(params1);
		// edtVidoUpdate.setLayoutParams(params1);
		edtKinhdo.setText(String.valueOf(currentMaker.getPosition().getLongitude()));
		edtVido.setText(String.valueOf(currentMaker.getPosition().getLatitude()));
		/*if (PopupWindowUpdate.isShowing()) {

		} */

		Log.e("bug", "getLongitude" + currentMaker.getPosition().getLongitude());
		Log.e("bug", "getLongitude" + currentMaker.getPosition().getLatitude());
		
		PopupWindowUpdate = new PopupWindow(popupViewUpdate,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		PopupWindowUpdate.showAtLocation(popupViewUpdate, Gravity.CENTER, 0, 0);
		PopupWindowUpdate.setFocusable(true);
		PopupWindowUpdate.update();
		btnExit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				PopupWindowUpdate.dismiss();
			}
		});
		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String LngUpdate = edtKinhdo.getText().toString().trim();
				String LatUpdate = edtVido.getText().toString().trim();
				if(edtKinhdo.length() !=0 && edtVido.length() != 0)/*{
					InfomationForm poleFrm = new InfomationForm();
			//		poleFrm.setId(_glb.getColId());
					poleFrm.setLatitude(poleLat);
					poleFrm.setLongtitude(poleLng);
					poleFrm.setCommit(commit);
					if(db.updateInfoCol(poleFrm)==0){
					Log.e("update pole", "success. ID_KEY = " + poleFrm.getId());
					Toast.makeText(getActivity(), "cập nhật vị trí thành công",
							Toast.LENGTH_SHORT).show();
					PopupWindowUpdate.dismiss();
					mapView.refresh();}
					else{
	 		        	 mLog.info("Update Poles Fail");}
					poleFrm.setLat(Double.parseDouble(poleLat));
					poleFrm.setLng(Double.parseDouble(poleLng));
					db.updateInfoCol(poleFrm);
				}*/
				
				{
					if ("Cột điện".equalsIgnoreCase(currentMaker.getTitle())) {
						db.updateObjectById(idUpdate, LatUpdate, LngUpdate,
								"POLES_LIST");
						// update cache position
						for (int i = 0; i < MapCache.listPole.size(); i++) {
							PoleForm poleFrm = MapCache.listPole.get(i);
							if (poleFrm.getIndex() == idUpdate) {
								poleFrm.setLat(Double.parseDouble(LatUpdate));
								poleFrm.setLng(Double.parseDouble(LngUpdate));
										
							//	mapView.refresh();
								break;
							}
				
						}
						
					}
					else if ("Nhà dân".equalsIgnoreCase(currentMaker.getTitle())) {
						db.updateObjectById(idUpdate, LatUpdate, LngUpdate,
								"HOUSE_LIST");
						// update cache position
						for (int i = 0; i < MapCache.listHouse.size(); i++) {
							HouseForm houseFrm = MapCache.listHouse.get(i);
							if (houseFrm.getId() == idUpdate) {
								houseFrm.setPoint(new LatLng(Double
										.parseDouble(LatUpdate), (Double
										.parseDouble(LngUpdate))));
								break;
							}
						}
					}
					else if ("Địa danh".equalsIgnoreCase(currentMaker.getTitle())) {
						db.updateObjectById(idUpdate, LatUpdate, LngUpdate, "PLACE_LIST");
						// update cache position
						for (int i = 0; i < MapCache.listPosition.size(); i++) {
							PositionForm positionFrm = MapCache.listPosition.get(i);
							if (positionFrm.getId() == idUpdate) {
								positionFrm.setPoint(new LatLng(Double
										.parseDouble(LatUpdate), (Double
										.parseDouble(LngUpdate))));
								break;
							}
						}
					}
					
					currentMaker.setPosition(new LatLng(Double
										.parseDouble(LatUpdate), (Double
										.parseDouble(LngUpdate))));
					Toast.makeText(getActivity(), "Cập nhật vị trí thành công",
							Toast.LENGTH_SHORT).show();
				PopupWindowUpdate.dismiss();
				mapView.refresh();
				// refresh
			//	ReloadMapFromCache(checkSwitch);
				}
				else createDialogValidate(Constant.MESSAGE_STR.UPDATE_FAIL_).show();
			}
		});
	}
	
	/*
	 * them moi cot dien anhpt edit
	 */
	private void showPopupPoles() {
		LayoutInflater layoutInflater = (LayoutInflater) getActivity()
				.getBaseContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);

		popupViewPoles = layoutInflater.inflate(R.layout.popup_insert_pole, null);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(displaymetrics);
		int width = displaymetrics.widthPixels / 10;
		TableRow.LayoutParams params1 = new TableRow.LayoutParams(width * 4,
				TableRow.LayoutParams.WRAP_CONTENT);

		txtMacotdien = (TextView) popupViewPoles
				.findViewById(R.id.txtMacotdien);
		txtLoaicotdien = (TextView) popupViewPoles
				.findViewById(R.id.txtLoaicotdien);
		txtChusohuu = (TextView) popupViewPoles.findViewById(R.id.txtChusohuu);

		txtSohodan = (TextView) popupViewPoles.findViewById(R.id.txtSohodan);
		txtGhichu = (TextView) popupViewPoles.findViewById(R.id.txtGhichu);

		txtKinhdo =(TextView) popupViewPoles.findViewById(R.id.txtkinhho);
		txtVido=(TextView) popupViewPoles.findViewById(R.id.txtvido);
		
		edtKinhdo = (EditText) popupViewPoles.findViewById(R.id.edtkinhho);
		edtVido = (EditText) popupViewPoles.findViewById(R.id.edtvido);
		if(MapCache.isToggle){
			edtKinhdo.setText(String.valueOf(geoPoint.getLongitude()));
			edtVido.setText(String.valueOf(geoPoint.getLatitude()));
		}
		else{
			edtKinhdo.setText(String.valueOf(gps.longitude));
			edtVido.setText(String.valueOf(gps.latitude));
		}
		edtMacotdien = (EditText) popupViewPoles
				.findViewById(R.id.edtMacotdien);
		edtSohodan = (EditText) popupViewPoles.findViewById(R.id.edtSohodan);
		edtGhichu = (EditText) popupViewPoles.findViewById(R.id.edtGhichu);
		edtDoCaoThietBi = (EditText) popupViewPoles.findViewById(R.id.edtDoCaoThietBi);

		btnSave = (Button) popupViewPoles.findViewById(R.id.btnSave);
		btnCancelPoles = (Button) popupViewPoles
				.findViewById(R.id.btnCancelPoles);
		rdoLoaicotdien = (RadioGroup) popupViewPoles
				.findViewById(R.id.rdoLoaicotdien);

		rdoChusohuu = (RadioGroup) popupViewPoles
				.findViewById(R.id.rdoChusohuu);
		rdoVuongdon = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoVuongdon);
		rdoVuongdoi = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoVuongdoi);
		rdoTrondon = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoTrondon);
		rdoTrondoi = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoTrondoi);
		rdoCotthep = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoCotthep);
		rdoCotgo = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoCotgo);
		rdoViettel = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoViettel);
		rdoVNPT = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoVNPT);
		rdoDienluc = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoDienluc);
		rdoXa = (RadioButton) popupViewPoles
				.findViewById(R.id.rdoXa);
		
		rdbTruoc = (RadioButton) popupViewPoles
				.findViewById(R.id.rdbTruoc);
		rdbSau = (RadioButton) popupViewPoles
				.findViewById(R.id.rdbSau);
		rdbTrai = (RadioButton) popupViewPoles
				.findViewById(R.id.rdbTrai);
		rdbPhai = (RadioButton) popupViewPoles
				.findViewById(R.id.rdbPhai);
		rdbKhongCo = (RadioButton) popupViewPoles
				.findViewById(R.id.rdbKhongCo);
		
		chkNewOrOld = (CheckBox) popupViewPoles.findViewById(R.id.chkNewOrOld);
		rdoVuongdon.setChecked(true);
		rdoDienluc.setChecked(true);
		txtMacotdien.setLayoutParams(new TableRow.LayoutParams(width * 2,
				TableRow.LayoutParams.WRAP_CONTENT));
		txtLoaicotdien.setLayoutParams(new TableRow.LayoutParams(width * 2,
				TableRow.LayoutParams.WRAP_CONTENT));
		txtChusohuu.setLayoutParams(new TableRow.LayoutParams(width * 2,
				TableRow.LayoutParams.WRAP_CONTENT));

		txtSohodan.setLayoutParams(new TableRow.LayoutParams(width * 2,
				TableRow.LayoutParams.WRAP_CONTENT));
		txtGhichu.setLayoutParams(new TableRow.LayoutParams(width * 2,
				TableRow.LayoutParams.WRAP_CONTENT));

		edtMacotdien.setLayoutParams(params1);
		edtSohodan.setLayoutParams(params1);
		edtGhichu.setLayoutParams(params1);

		btnSave.setLayoutParams(params1);

		rdoLoaicotdien.setLayoutParams(params1);
		rdoChusohuu.setLayoutParams(params1);
		chkNewOrOld.setLayoutParams(params1);
		
		PopupWindowPole = new PopupWindow(popupViewPoles,
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

		PopupWindowPole.showAtLocation(popupViewPoles, Gravity.CENTER, 0, 0);
		PopupWindowPole.setFocusable(true);
		PopupWindowPole.update();
		btnCancelPoles.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				PopupWindowPole.dismiss();
			}
		});
		/*
		 * Log.v("gia tri cua lon ", String.valueOf(lon));
		 * Log.v("gia tri cua lat ", String.valueOf(lat));
		 * Log.v("toggleeee",Boolean.toString(MapCache.isToggle));
		 */
		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (MapCache.isToggle) {
					savePoleToDB(lon, lat);
				} else {
					savePoleToDB(gps.longitude, gps.latitude);
				}

			}
		});

	}

	// anhpt67: save a pole to database
	// @param longtitude
	// @param latitude
	// longtitude and latitude values of pole position

	private void savePoleToDB(double longitude, double latitude) {
		// Radio loai cot dien
		// showPopup = false;
		int selectedColTypeId = rdoLoaicotdien.getCheckedRadioButtonId();
		rbLoaicotdien = (RadioButton) popupViewPoles
				.findViewById(selectedColTypeId);

		String Lng = edtKinhdo.getText().toString().trim();
		String Lat = edtVido.getText().toString().trim();
		
		// Radio chu so huu
		int selectedOwnerId = rdoChusohuu.getCheckedRadioButtonId();
		rbChusohuu = (RadioButton) popupViewPoles.findViewById(selectedOwnerId);

		final InfomationForm info = new InfomationForm();
		// Ma cot
		if(edtMacotdien.getText().toString().trim().equals("")){
			info.setCol_code("UNKNOW");
		} else {
			info.setCol_code(edtMacotdien.getText().toString().trim());
		}

		//kinh do vi do
		info.setPosition(2);
		info.setLatitude(String.valueOf(Lat));
		info.setLongtitude(String.valueOf(Lng) );
		
		// Ghi chu
		info.setNote(edtGhichu.getText().toString().trim());

		// SO ho dan
		if (edtSohodan.getText().toString().trim().length() > 0) {
			info.setNum_people(edtSohodan.getText().toString().trim());
		} else {
			info.setNum_people("");
		}

		// Loai cot
		if (rdoVuongdon.isChecked()) {
			info.setCol_type(Constant.POLES_TYPE.VuongDon);
		}
		if (rdoVuongdoi.isChecked()) {
			info.setCol_type(Constant.POLES_TYPE.VuongDoi);
		}
		if (rdoTrondon.isChecked()) {
			info.setCol_type(Constant.POLES_TYPE.TronDon);
		}
		if (rdoTrondoi.isChecked()) {
			info.setCol_type(Constant.POLES_TYPE.TronDoi);
		}
		if (rdoCotthep.isChecked()) {
			info.setCol_type(Constant.POLES_TYPE.CotThep);
		}
		if (rdoCotgo.isChecked()) {
			info.setCol_type(Constant.POLES_TYPE.CotGo);
		}

		// Chu so huu
		if (rdoViettel.isChecked()) {
			info.setOwner(Constant.POLES_OWNER.Viettel);
		}
		if (rdoVNPT.isChecked()) {
			info.setOwner(Constant.POLES_OWNER.VNPT);
		}
		if (rdoDienluc.isChecked()) {
			info.setOwner(Constant.POLES_OWNER.DienLuc);
		}
		if (rdoXa.isChecked()) {
			info.setOwner(Constant.POLES_OWNER.Xa);
		}

		// Moi hay cu

		if (chkNewOrOld.isChecked()) {
			info.setNeworold(Constant.NEW_OR_OLD.New);
		} else {
			info.setNeworold(Constant.NEW_OR_OLD.Old);
		}
		if(!edtDoCaoThietBi.getText().toString().trim().equals("")){
			info.setDoCaoThietBi(edtDoCaoThietBi.getText().toString().trim());
		} else {
			info.setDoCaoThietBi("");
		}
		
		// Vi tri thiet bi
		if(rdbTruoc.isChecked()){
			info.setViTriThietBi("1");
		} else
		if(rdbSau.isChecked()){
			info.setViTriThietBi("2");
		} else
		if(rdbTrai.isChecked()){
			info.setViTriThietBi("3");
		} else
		if(rdbPhai.isChecked()){
			info.setViTriThietBi("4");
		} else {
			info.setViTriThietBi("-1");
		}

		// Vi tri
		//info.setPosition(2);
		//info.setLatitude(String.valueOf(latitude));
		//info.setLongtitude(String.valueOf(longitude));
		boolean check = true;
		int id;
		//if (validatePoles() == true && check == true) {
			if ((id = db.insertInfoCol(info)) != -1) {
				// map cache
				PoleForm poleFrm = new PoleForm();
				poleFrm.setLat(Double.parseDouble(Lat));
				poleFrm.setLng(Double.parseDouble(Lng));
				poleFrm.setIndex(id);
				MapCache.listPole.add(poleFrm);

				Log.e("insertPoles", "success. ID_KEY = " + id);
				MarkerOptions opts1 = new MarkerOptions()
						.position(new LatLng(Double.parseDouble(Lat), Double.parseDouble(Lng)))
						.title("Cột điện").zIndex(id).rotation(0)
						.icon(BitmapFactory
								.decodeResource(
										getResources(),
										checkSwitch ? R.drawable.electricity_icon_larger
												: R.drawable.pole_24));
				mapView.addMarker(opts1);
				//ReloadMapFromCache(checkSwitch);
				mapView.refresh();
				clearForm();
				Toast.makeText(getActivity(), "Thêm cột thành công",
						Toast.LENGTH_SHORT).show();
				PopupWindowPole.dismiss();

			} else {
				// createDialogValidate(Constant.MESSAGE_STR.UPDATE_FAIL).show();
				createDialogValidate("Thêm cột không thành công").show();
			}
		}
	
	/*
	 * check radio 
	 */
	void checkRadioGroup() {
		rdoLoaicotdien.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {
				checkedId = group.getCheckedRadioButtonId();
				switch (checkedId) {
				case R.id.rdoVuongdon:
					
					break;

				case R.id.rdoVuongdoi:
					break;

				case R.id.rdoTrondon:
					
					break;
				case R.id.rdoTrondoi:
					
					break;
				case R.id.rdoCotthep:
					
					break;
				case R.id.rdoCotgo:
					
					break;

				default:
					break;
				}
			}
		});

	}

//	private Marker touchMarker;

	// tinh khoang cach giua 2 diem: cham va gps
	public double CalDistance(double latitude1, double longitude1,
			double latitude2, double longitude2) {
		int Radius = 6371; // radius of earth in km
		double lat1 = latitude1;
		double lat2 = latitude2;
		double lon1 = longitude1;
		double lon2 = longitude2;
		double dLat = Math.toRadians(lat2 - lat1);
		double dLon = Math.toRadians(lon2 - lon1);
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
				+ Math.cos(Math.toRadians(lat1))
				* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
				* Math.sin(dLon / 2);
		double c = 2 * Math.asin(Math.sqrt(a));
		double valueResult = Radius * c * 1000;
		double km = valueResult / 1;
		DecimalFormat newFormat = new DecimalFormat("####");
		int kmInDec = Integer.valueOf(newFormat.format(km));
		double meter = valueResult % 1000;
		int meterInDec = Integer.valueOf(newFormat.format(meter));
		Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
				+ " Meter   " + meterInDec);

		return valueResult;
		// return meterInDec;
	}

	// ve duong bang mode ve tay
	private LatLng mapPointLast = null;

	public void drawRoadToggleOn(double longitude, double latitude) {
		LatLng mapPoint = new LatLng(latitude, longitude);
			// ve them 1 diem
			if (listPointOfCurrentRoad.size() == 1) {
				_glb.setCachePoint(mapPoint);
				listPointOfCurrentRoad.add(mapPoint);
				currentRoad.add(new LatLng(latitude, longitude))
						.strokeColor(Color.parseColor("#63D60A"))
						.strokeWidth(15);
				// set cache angle
				_glb.setCacheAngle(MapFunction.getLineAngle(
						_glb.getCurrentComparePoint(), mapPoint));

			} else {
				listPointOfCurrentRoad.add(mapPoint);
				currentRoad.add(new LatLng(latitude, longitude))
						.strokeColor(Color.parseColor("#63D60A"))
						.strokeWidth(15);
			}
	}

	private void showFunctionsButtons() {
		// The toggle is enabled
		rootView.findViewById(R.id.header).setVisibility(View.VISIBLE);
		ibnStart.setVisibility(View.INVISIBLE);
		// ibnPause.setVisibility(View.INVISIBLE);
		ibnRoad.setVisibility(View.VISIBLE);

	}

	private void hideFunctionsButtons() {
		rootView.findViewById(R.id.header).setVisibility(View.GONE);
		ibnStart.setVisibility(View.GONE);
		ibnRoad.setVisibility(View.GONE);
	}

	/*
	 * Load Positon
	 */

	private void loadPositionToMap(List<InfomationForm> lstPosition,
			boolean clearCache) {
		// Clear cache
		if (clearCache)
			MapCache.lstPolylineOptions.clear();

		PolylineOptions opts2 = new PolylineOptions();
		opts2.strokeWidth(15);
		ArrayList<LatLng> points = new ArrayList<LatLng>();
		if (lstPosition.size() > 0) {
			for (InfomationForm obj : lstPosition) {
				points.add(new LatLng(Double.parseDouble(obj.getLatitude()),
						Double.parseDouble(obj.getLongtitude())));

				Log.e("fr", obj.getLatitude() + "-" + obj.getLongtitude());
			}
			opts2.addAll(points);
			mapView.addPolyline(opts2);

			// Load to Cache
			MapCache.lstPolylineOptions.add(opts2.clone());

		}
	}

	/*
	 * Load House
	 */

	private void loadHouseToMap(List<InfomationForm> lstHouse) {
		// Clear cache
		MapCache.listHouse.clear();

		for (InfomationForm obj : lstHouse) {
			MarkerOptions opts1 = new MarkerOptions()
					.position(
							new LatLng(Double.parseDouble(obj.getLatitude()),
									Double.parseDouble(obj.getLongtitude())))
					.title("Nhà dân")
					.icon(BitmapFactory.decodeResource(getResources(),
							checkSwitch ? R.drawable.house_finger_larger
									: R.drawable.house_24)).rotation(0);
			mapView.addMarker(opts1);

			// Load to cache
			HouseForm houseFrm = new HouseForm();
			houseFrm.setId(obj.getId());
			houseFrm.setPoint(new LatLng(Double.parseDouble(obj.getLatitude()),
					Double.parseDouble(obj.getLongtitude())));
			MapCache.listHouse.add(houseFrm);

		}
	}

	/*
	 * Load Poles
	 */

	private void loadPolesToMap(List<InfomationForm> lstPoles) {
		// Clear cache
		MapCache.listPole.clear();

		for (InfomationForm obj : lstPoles) {
			MarkerOptions opts1 = new MarkerOptions()
								.position(
							new LatLng(Double.parseDouble(obj.getLatitude()),
									Double.parseDouble(obj.getLongtitude())))
					.title("Cột điện")
					.icon(BitmapFactory.decodeResource(getResources(),
							checkSwitch ? R.drawable.electricity_icon_larger
									: R.drawable.pole_24)).rotation(0);
			mapView.addMarker(opts1);
			Log.e("TEST", "opts1======"+ opts1.getTitle());

			// Load to cache
			
			PoleForm poleFrm = new PoleForm();
			poleFrm.setIndex(obj.getId());
			poleFrm.setLat(Double.parseDouble(obj.getLatitude()));
			poleFrm.setLng(Double.parseDouble(obj.getLongtitude()));
			
			Log.e("TEST", "ID LAT LNG"+ poleFrm.getIndex());
			Log.e("TEST", "ID LAT LNG"+ poleFrm.getLat());
			Log.e("TEST", "ID LAT LNG"+ poleFrm.getLng());
			
			MapCache.listPole.add(poleFrm);

		}
	}

	/*
	 * Load Place to Map
	 */

	private void loadPlaceToMap(List<InfomationForm> lstPlace) {
		for (InfomationForm obj : lstPlace) {
			MarkerOptions opts1 = new MarkerOptions()
					.position(
							new LatLng(Double.parseDouble(obj.getLatitude()),
									Double.parseDouble(obj.getLongtitude())))
					.title("Địa danh")
					.icon(BitmapFactory.decodeResource(getResources(),
							checkSwitch ? R.drawable.place_icon_larger
									: R.drawable.place_24)).rotation(0);
			mapView.addMarker(opts1);

			// load to cache
			PositionForm positionFrm = new PositionForm();
			positionFrm.setId(obj.getId());
			positionFrm.setPoint(new LatLng(Double.parseDouble(obj
					.getLatitude()), Double.parseDouble(obj.getLongtitude())));
			positionFrm.setPlaceName(obj.getPlaceName());
			positionFrm.setPlaceNote(obj.getPlaceNote());
			MapCache.listPosition.add(positionFrm);

		}
	}

	/*
	 * Reload Map By Datetime
	 */

	public void reloadMapByDate(java.util.Date date) {

		if (mapView != null)
			mapView.clear();
		//mr tranthang edit
		MapCache.listHouse.clear();
		MapCache.listPole.clear();
		MapCache.listPosition.clear();
		MapCache.lstPolylineOptions.clear();
			
		
		txtViewBottom.setText("00:00:00");
		// anhpt edit
		if (MapCache.isToggle)
			rootView.findViewById(R.id.header).setVisibility(View.VISIBLE);
		else
			rootView.findViewById(R.id.header).setVisibility(View.GONE);
		Log.e("date", date.toGMTString());
		// lay danh sach duong
		List<InfomationForm> lstTimeStop = db.getTimeStopByDate(date);
		Log.e("count", String.valueOf(lstTimeStop.size()));
		if (lstTimeStop.size() > 0) {
			boolean flag = true;
			for (InfomationForm obj : lstTimeStop) {
				// voi moi duong, lay danh sach diem
				List<InfomationForm> lstPosition = db.getPositionByTime(obj
						.getId());
				Log.e("count", String.valueOf(lstPosition.size()));
				if (flag) {
					loadPositionToMap(lstPosition, true);
					flag = false;
				} else {
					loadPositionToMap(lstPosition, false);
				}
				
			}
		}

		List<InfomationForm> lstHouse = db.getHouseByDate(date);
		Log.e("count house", String.valueOf(lstHouse.size()));
		if (lstHouse.size() > 0) {
			loadHouseToMap(lstHouse);
		}

		List<InfomationForm> lstPoles = db.getPoleByDate(date);
		Log.e("count poles", String.valueOf(lstPoles.size()));
		if (lstPoles.size() > 0) {
			loadPolesToMap(lstPoles);
		}

		List<InfomationForm> lstPlace = db.getPlaceByDate(date);
		Log.e("count place", String.valueOf(lstPlace.size()));
		if (lstPlace.size() > 0) {
			loadPlaceToMap(lstPlace);
		}
		ReloadMapFromCache(checkSwitch);// <-- note: zindex của marker luôn =0 nếu bỏ line này 
		mapView.refresh();

	}

	private void showSelectionDatePopup() {

		Calendar cal = Calendar.getInstance();
		int day = cal.get(Calendar.DAY_OF_MONTH);
		int month = cal.get(Calendar.MONTH);
		int year = cal.get(Calendar.YEAR);

		DatePickerDialog dialog = new DatePickerDialog(getActivity(),
				datePickerListener, year, month, day);
		
		Log.i("DATA", "show dialog thoi gian");
		dialog.show();
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date date;
			try {
				date = sdf.parse(String.valueOf(selectedYear) + "-"
						+ String.valueOf(selectedMonth + 1) + "-"
						+ String.valueOf(selectedDay));

				// Toast.makeText(getActivity(),sdf.format(date),Toast.LENGTH_SHORT).show();
//				Log.e("dataaaa", "date="+date);
				
				reloadMapByDate(date);
				mLog.info("Reloading Map Completed.");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/*
	 * alert closed form insert poles
	 */
	public AlertDialog createDialogErrorNotReturn(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("Thông báo");
		builder.setMessage(msg);
		builder.setCancelable(false);

		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				PopupWindowPole.dismiss();
			}
		});
		AlertDialog dialog = builder.create();
		return dialog;
	}

	/*
	 * clear form insert poles
	 */
	public void clearForm() {

		edtMacotdien.setText("");
		edtGhichu.setText("");
		edtSohodan.setText("0", BufferType.EDITABLE);
		edtSohodan.getText().clear();
	}

	private boolean validatePoles() {
		if (edtMacotdien.getText().toString().trim().length() < 1) {
			createDialogValidate(Constant.MESSAGE_STR.POLES_CODE_REQUIED)
					.show();
			return false;
		}

		return true;
	}

	public AlertDialog createDialogValidate(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("Thông báo");
		builder.setMessage(msg);
		builder.setCancelable(false);

		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		AlertDialog dialog = builder.create();
		return dialog;
	}

	/*
	 * Load ban do khi chon track list
	 */

	public void reloadMap(int timeListId) {
		if (mapView != null)
			mapView.clear();
		txtViewBottom.setText("00:00:00");
		rootView.findViewById(R.id.header).setVisibility(View.GONE);
		Log.e("timeListId", String.valueOf(timeListId));
		if (timeListId != 0) {
			List<InfomationForm> lstPosition = db.getPositionByTime(timeListId);
			Log.e("count", String.valueOf(lstPosition.size()));
			loadPositionToMap(lstPosition, true);

			List<InfomationForm> lstHouse = db.getHouseByTime(timeListId);
			Log.e("count house", String.valueOf(lstHouse.size()));
			if (lstPosition.size() > 0) {
				loadHouseToMap(lstHouse);
			}

			List<InfomationForm> lstPoles = db.getAllCol();
			Log.e("count poles", String.valueOf(lstPoles.size()));
			if (lstPoles.size() > 0) {
				loadPolesToMap(lstPoles);
			}

			List<InfomationForm> lstPlace = db.getPlaceByTime(timeListId);
			Log.e("count place", String.valueOf(lstPlace.size()));
			if (lstPosition.size() > 0) {
				loadPlaceToMap(lstPlace);
			}
		}
		mapView.refresh();
	}
}

// mapView.setZoom(mapView.getZoom(), false);